<?php namespace Home\Controller; 

use Hdphp\Controller\Controller;
use Home\Model\Pay;

class PayController extends Controller
{
	protected $db;

	//构造函数
	public function __init()
	{
		$this->db = new Pay;
	}
	
    //动作
    public function pay(){
		$confirm = $_POST['goods'];
		foreach ($confirm as $key => $value) {
			if(isset($value))
			{
				$tmp = $_SESSION['confirm'][$value];
			}
			$data[] = $tmp;
		}

		$postAddr = Db::table('shop_postaddress')->where('uid',$_SESSION['id'])->get();
    	$addr = array();
    	foreach($postAddr as $key => $value){
    		$all = explode('-',$value['postaddress']);
    		$value['sheng'] = $all[0];
    		$value['shi'] = $all[1];
    		$value['qu'] = $all[2];
    		$value['address'] = $all[3];
    		$addr[] = $value;
    	}
    	View::with('data',$data);
    	View::with('addr',$addr);
    	View::make();
    }

    public function paydone()
    {
    	if(IS_POST)
    	{
    		//组合订单表需要的数据
    		$postaddr = Db::table('shop_postaddress')->where('id',$_POST['postAddress'])->first();
    		$data = array();
    		$data['order_sn']= 'H'.date('YmdHis',time());
    		$data['order_cash'] = $_POST['allpay'];
    		$data['remark'] = $_POST['postType'];
    		$data['create_time'] = time();
    		$data['order_status'] = '0';
    		$data['postname'] = $postaddr['postname'];
    		$data['postaddress'] = $postaddr['postaddress'];
    		$data['hd_shop_user_id'] = $postaddr['uid'];

    		//组合订单列表需要的数据
    		$list = array();
    		foreach ($_SESSION['confirm'] as $key => $value) {
    			$tmp['total'] = $value['total'];
    			$tmp['size'] = $value['size'];
    			$tmp['minprice'] = $value['minprice'];
    			$tmp['thumb_pic'] = $value['thumb_pic'];
    			$tmp['remark'] = $_POST['postType'];
    			$tmp['hd_shop_goods_goods_id'] = $value['goods_id'];
    			$tmp['hd_shop_order_order_sn'] = $data['order_sn'];
    			$list[$key] = $tmp;
    		}

    		//分别写入数据库
    		if($_SESSION['oid'] = $this->db->store($data)){
    			foreach ($list as $key => $value) {
    				$value['hd_shop_order_oid'] = $_SESSION['oid'];
    				//实例化订单列表模型
    				$orderlist = new \Home\Model\Orderlist;
    				// 压入数据库成功后删除购物车与post数据
    				if($orderlist->store($value))
    				{
    					unset($_SESSION['joinCart'][$key]);
    					unset($_SESSION['confirm'][$key]);
    					unset($_POST);
    				}
    			}
    			View::success('订单提交成功',U('Ordersuccess/index'));
    		}
    	}
    }
}
